﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZSZ.DTO;
using ZSZ.IService;
using ZSZ.Model;

namespace ZSZ.Service
{
    public partial class PermissionService : BaseService<Permission>, IPermissionService
    {
        /// <summary>
        /// 权限名称是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Exist(string name)
        {
            return GetAll().Any(p => p.Name == name); ;
        }

        public PermissionDTO[] GetPermissions()
        {
            return GetAll().ToList().Select(p => ToDTO(p)).ToArray();
        }

        public PermissionDTO GetDTOById(long id)
        {
            Permission entity = GetById(id);
            if (entity==null)
            {
                throw new Exception("获取不到权限(Id:" + id + ")信息");
            }
            return ToDTO(entity);
        }

        /// <summary>
        /// 角色拥有权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public PermissionDTO[] GetPermissionByRoleId(long roleId)
        {
            //角色是否存在
            Role role = DbSession.RoleDal.GetById(roleId);
            if (role == null)
            {
                throw new ArgumentException("roleId 不存在" + roleId);
            }
            return role.RolePermissions.Select(rp => ToDTO(rp.Permission)).ToArray();
        }

        private PermissionDTO ToDTO(Permission entity)
        {
            PermissionDTO dto = new PermissionDTO();
            dto.CreateDateTime = entity.CreateDateTime;
            dto.Id = entity.Id;
            dto.Name=entity.Name;
            dto.Description=entity.Description;
            dto.ControllerName=entity.ControllerName;
            dto.ActionName=entity.ActionName;
            dto.HttpMethod=entity.HttpMethod;
            return dto;
        }

        public void Add(string name, string description, string controllerName, string actionName, string httpMethod)
        {
            Permission entity = new Permission();
            entity.Name = name;
            entity.Description = description;
            entity.ControllerName = controllerName;
            entity.ActionName = actionName;
            entity.HttpMethod = httpMethod;
            Add(entity);
        }
        public void Update(long id, string name, string description, string controllerName, string actionName, string httpMethod)
        {
            Permission entity = GetById(id);
            if (entity==null)
            {
                throw new Exception("获取不到权限(id:"+id+")信息");
            }
            entity.Name = name;
            entity.Description = description;
            entity.ControllerName = controllerName;
            entity.ActionName = actionName;
            entity.HttpMethod = httpMethod;
            Update(entity);
        }
    }
}
